package com.mdp;

import com.alibaba.fastjson.JSONObject;
import com.mdp.im.core.utils.msg.Action;
import com.mdp.im.core.utils.msg.MsgType;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.URI;

public class ClientMain2 {
    public static void main(String[] args) throws Exception{
        EventLoopGroup group=new NioEventLoopGroup();
        Bootstrap boot=new Bootstrap();
        boot.option(ChannelOption.SO_KEEPALIVE,true)
                .option(ChannelOption.TCP_NODELAY,true)
                .option(ChannelOption.SO_BACKLOG,1024*1024*10)
                .group(group)
                .handler(new LoggingHandler(LogLevel.INFO))
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline p = socketChannel.pipeline();
                        p.addLast(new ChannelHandler[]{new HttpClientCodec(),
                                new HttpObjectAggregator(1024*1024*10)});
                        p.addLast("hookedHandler", new com.mdp.WebSocketClientHandler());
                    }
                });
        String accessToken="";
        URI websocketURI = new URI("ws://localhost:3333/ws?access_token="+accessToken);
        HttpHeaders httpHeaders = new DefaultHttpHeaders();
        //进行握手
        WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(websocketURI, WebSocketVersion.V13, (String)null, true,httpHeaders);
        System.out.println("connect");
        final Channel channel=boot.connect(websocketURI.getHost(),websocketURI.getPort()).sync().channel();
        com.mdp.WebSocketClientHandler handler = (com.mdp.WebSocketClientHandler)channel.pipeline().get("hookedHandler");
        handler.setHandshaker(handshaker);
        handshaker.handshake(channel);
        //阻塞等待是否握手成功
        handler.handshakeFuture().sync();
 
        Thread privateMessageRead=new Thread(new Runnable() {
            public void run() {
                int i=30;
                  for(;;) {
                	  System.out.println("text send");
                      JSONObject message = new JSONObject();
                      message.put("action", Action.HIS_MESSAGE);
                      message.put("msgType", MsgType.PRICHAT);
                      message.put("sendUserid", "cycsir2");
                      message.put("toUserid", "cycsir"); 
                      JSONObject queryParams=new JSONObject();
                      queryParams.put("sendUserid", "cycsir2");
                      queryParams.put("toUserid", "cycsir"); 
                      queryParams.put("key", "%cyc%");
                      queryParams.put("pageNum", "1");
                      queryParams.put("pageSize", 10);
                      message.put("queryParams", queryParams);
                      TextWebSocketFrame frame = new TextWebSocketFrame(message.toJSONString());
                      channel.writeAndFlush(frame).addListener(new ChannelFutureListener() {
                          public void operationComplete(ChannelFuture channelFuture) throws Exception {
                              if(channelFuture.isSuccess()){
                                  System.out.println("text send success");
                              }else{
                                  System.out.println("text send failed  "+channelFuture.cause().getMessage());
                              }
                          }
                      });
                  	try {
  						Thread.sleep(10000);
  					} catch (InterruptedException e) {
  						// TODO Auto-generated catch block
  						e.printStackTrace();
  					}
                  }
                   
                }
        });

        Thread groupMessageRead=new Thread(new Runnable() {
            public void run() {
                int i=30;
                  for(;;) {
                	  System.out.println("text send");
                      JSONObject message = new JSONObject();
                      message.put("action", Action.HIS_MESSAGE);
                      message.put("msgType", MsgType.GROUP);
                      message.put("sendUserid", "cycsir");
                      message.put("groupId", "cycsirGroup1"); 
                      JSONObject queryParams=new JSONObject();
                      queryParams.put("sendUserid", "cycsir2");
                      queryParams.put("groupId", "cycsirGroup1"); 
                      queryParams.put("key", "%cyc%");
                      queryParams.put("pageNum", "1");
                      queryParams.put("pageSize", 10);
                      message.put("queryParams", queryParams);
                      TextWebSocketFrame frame = new TextWebSocketFrame(message.toJSONString());
                      channel.writeAndFlush(frame).addListener(new ChannelFutureListener() {
                          public void operationComplete(ChannelFuture channelFuture) throws Exception {
                              if(channelFuture.isSuccess()){
                                  System.out.println("text send success");
                              }else{
                                  System.out.println("text send failed  "+channelFuture.cause().getMessage());
                              }
                          }
                      });
                  	try {
  						Thread.sleep(10000);
  					} catch (InterruptedException e) {
  						// TODO Auto-generated catch block
  						e.printStackTrace();
  					}
                  }
                   
                }
        });
        

        Thread sysMessageRead=new Thread(new Runnable() {
            public void run() {
                int i=30;
                  for(;;) {
                	  System.out.println("text send");
                      JSONObject message = new JSONObject();
                      message.put("action", Action.HIS_MESSAGE);
                      message.put("msgType", MsgType.SYS);
                      message.put("sendUserid", "cycsir");
                      JSONObject queryParams=new JSONObject();
                      queryParams.put("sendUserid", "cycsir2");  
                      queryParams.put("key", "%cyc%");
                      queryParams.put("pageNum", "1");
                      queryParams.put("pageSize", 10);
                      message.put("queryParams", queryParams);
                      TextWebSocketFrame frame = new TextWebSocketFrame(message.toJSONString());
                      channel.writeAndFlush(frame).addListener(new ChannelFutureListener() {
                          public void operationComplete(ChannelFuture channelFuture) throws Exception {
                              if(channelFuture.isSuccess()){
                                  System.out.println("text send success");
                              }else{
                                  System.out.println("text send failed  "+channelFuture.cause().getMessage());
                              }
                          }
                      });
                  	try {
  						Thread.sleep(10000);
  					} catch (InterruptedException e) {
  						// TODO Auto-generated catch block
  						e.printStackTrace();
  					}
                  }
                   
                }
        });
        privateMessageRead.start();
        groupMessageRead.start();
        sysMessageRead.start();
    }
}